/**
 * 
 */
package recognition.engine;

import handwritten.character.RawHandWrittenCharacter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;

import recognition.input.Input;
import recognition.output.PredictedCharacter;
import recognition.preprocessor.Preprocessor;
import recognition.processor.Processor;

/**
 * @author Louis
 *
 */
public class RecognitionEngine {
	
	private Preprocessor ppRoot;
	
	private ArrayList<Recognizer> recognizers;
	private int limit;
	
	public RecognitionEngine(Preprocessor ppRoot, int limit){
		this.limit = limit;
		this.ppRoot = ppRoot;
		recognizers = new ArrayList<Recognizer>();
	}
	
		
	
	public void addRecognizer(Recognizer r){
		recognizers.add(r);
	}
	
	/*protected Preprocessor getPproot(){
		return ppRoot;
	}*/
	
	public Preprocessor getPpRoot()
	{
		return ppRoot;
	}
	
	public ArrayList<PredictedCharacter> recognize(RawHandWrittenCharacter rwc){
		
		Hashtable<Class<? extends Input<?>>,Input<?>> inputs = new Hashtable<Class<? extends Input<?>>,Input<?>>();
		
		if(ppRoot !=null)
			ppRoot.preprocess(rwc.getGesture(), inputs);
			
		
		ArrayList<PredictedCharacter> results = new ArrayList<PredictedCharacter>();
		ArrayList<PredictedCharacter> tmp;
		int index;
		
		for(Recognizer r : recognizers){
			tmp = r.process(inputs);
			
			for(PredictedCharacter pc : tmp){
				index = results.indexOf(pc);
				if(index != -1){
					results.get(index).addConfidence(r.getStrength(), pc.getConfidence());
				} else {
					results.add(new PredictedCharacter(pc.getId(),r.getStrength()*pc.getConfidence()));
				}
			}

		}
		//FIXME if results is empty code block here
		Collections.sort(results);
		if(limit <= 0 || limit > results.size())
			return results;
		
		
		for(int i = limit; i<results.size();)
			results.remove(i);
		
		return results;
	}
	

}
